package com.jing.weibo.controller.fansattention;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.model.User;
import weibo4j.model.WeiboException;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.FansAttentionType;
import com.jing.weibo.pojo.fans.Fansattention;
import com.jing.weibo.pojo.user.UserInfo;
import com.jing.weibo.service.fans.FansAttentionService;
import com.jing.weibo.ws.sina.FriendshipsService;

/**
 * 用户粉丝的Controller
 * @author jing.yue
 * @version 2012/08/29 1.0.0
 */
@Controller
public class FansController extends BaseController {

	private static final Logger logger = Logger.getLogger(FansController.class);

	@Autowired
	private FriendshipsService friendshipsService;
	@Autowired
	private FansAttentionService fansAttentionService;

	/**
	 * 同步用户粉丝
	 * @return
	 */
	@RequestMapping(value = "/fans/json/synchrologFans")
	@ResponseBody
	public ModelMap synchrologFans(HttpServletRequest request, Integer synchrologNum) {
		String result = null;
		String weiboMsg = null;
		UserInfo userInfo = getSessionUser(request);
		try {
			//同步次数
			for (int i = 0; i < synchrologNum.intValue(); i++) {
				synchrologInfo(request, FansAttentionType.TYPE_FANS);
			}
			logger.info(userInfo.getNickname() + "同步用户粉丝: SUCCESS");
			result = SUCCESS;
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e));
			result = ERROR_WEIBO;
			weiboMsg = WeiboCons.getErrorMsg(e);
		} catch (Exception e) {
			logger.error("同步用户粉丝信息异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}

	/**
	 * 获取用户单向粉丝列表
	 * @return
	 */
	@RequestMapping(value = "/fans/json/onewayFans")
	@ResponseBody
	public ModelMap onewayFans(HttpServletRequest request, Fansattention fansattention) {
		String result = null;
		String weiboMsg = null;
		Map<String, Object> map = null;
		try {
			synchrologInfo(request, FansAttentionType.TYPE_FANS);
			fansattention.setType(FansAttentionType.TYPE_FANS.getCode());
			fansattention.setUsername(getSessionUser(request).getUsername());
			map = fansAttentionService.findOnewayFans(fansattention);
			result = SUCCESS;
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e));
			result = ERROR_WEIBO;
			weiboMsg = WeiboCons.getErrorMsg(e);
		} catch (Exception e) {
			logger.error("获取单向粉丝信息异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}

	/**
	 * 获取用户粉丝列表
	 * @return
	 */
	@RequestMapping(value = "/fans/json/myFans")
	@ResponseBody
	public ModelMap myFans(HttpServletRequest request, Fansattention fansattention) {
		String result = null;
		String weiboMsg = null;
		Map<String, Object> map = null;
		try {
			synchrologInfo(request, FansAttentionType.TYPE_FANS);
			fansattention.setFollowme("true");
			fansattention.setType(FansAttentionType.TYPE_FANS.getCode());
			fansattention.setUsername(getSessionUser(request).getUsername());
			map = fansAttentionService.findFans(fansattention);
			result = SUCCESS;
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e));
			result = ERROR_WEIBO;
			weiboMsg = WeiboCons.getErrorMsg(e);
		} catch (Exception e) {
			logger.error("获取粉丝信息异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}

	/**
	 * 获取用户互粉粉丝列表
	 * @return
	 */
	@RequestMapping(value = "/fans/json/mutualPowderFans")
	@ResponseBody
	public ModelMap mutualPowderFans(HttpServletRequest request, Fansattention fansattention) {
		String result = null;
		String weiboMsg = null;
		Map<String, Object> map = null;
		try {
			synchrologInfo(request, FansAttentionType.TYPE_FANS);
			fansattention.setType(FansAttentionType.TYPE_FANS.getCode());
			fansattention.setUsername(getSessionUser(request).getUsername());
			fansattention.setFollowing("true");
			fansattention.setFollowme("true");
			map = fansAttentionService.findFans(fansattention);
			result = SUCCESS;
		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e));
			result = ERROR_WEIBO;
			weiboMsg = WeiboCons.getErrorMsg(e);
		} catch (Exception e) {
			logger.error("获取互粉粉丝信息异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("data", map);
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg);
		return modelMap;
	}

	/**
	 * 关注粉丝的用户
	 * @return
	 */
	@RequestMapping(value = "/fans/json/attentionFans")
	@ResponseBody
	public ModelMap attentionFans(HttpServletRequest request, Fansattention fansattention, String uids, String opterType) {
		String result = null;
		StringBuffer weiboMsg = new StringBuffer();
		StringBuffer errorWeiboMsg = new StringBuffer();
		UserInfo userInfo = getSessionUser(request);
		int count = 0;
		int errorCount = 0;
		User user = null;
		String[] uidArr = uids.split(",");
		for (String uid : uidArr) {
			if(uid == null || "".equals(uid.trim())) {
				continue;
			}
			fansattention.setUsername(userInfo.getUsername());
			fansattention.setFansattentionusername(uid);
			try {
				user = friendshipsService.createFriendshipsById(uid, userInfo.getToken());
				opterFansatention(opterType, fansattention, user);
			} catch (WeiboException e) {
				logger.error(WeiboCons.getErrorMsg(e));
				result = ERROR_WEIBO;
				errorWeiboMsg.append("调用微博接口关注[").append(uid).append("]用户出现异常[").append(WeiboCons.getErrorMsg(e)).append("]!");
				errorCount ++;
			} catch (Exception e) {
				logger.error("关注单向粉丝信息异常!", e);
				errorCount ++;
			}
			count ++;
		}
		weiboMsg.append("共关注[").append(count).append(")]位用户: [").append(count - errorCount).append("]位成功! [").append(errorCount).append("]位失败!");
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("weiboMsg", weiboMsg.toString());
		modelMap.put("errorWeiboMsg", errorWeiboMsg.toString());
		return modelMap;
	}

	/**
	 * 操作用户
	 * @param opterType
	 * @param fansattention
	 * @param user
	 * @throws Exception
	 */
	private void opterFansatention(String opterType, Fansattention fansattention, User user) throws Exception {
		//单向粉丝
		if("onewayFans".equals(opterType)) {
			//关注后将变成单向粉丝变成互粉粉丝
			fansattention.setFollowing("true");
			fansAttentionService.updateFansattentionFollow(fansattention);
			//新增关注记录
			Fansattention fa = fansAttentionService.findByUsernameFansname(fansattention).get(0);
			fa.setFollowing("true");
			fa.setFollowme("true");
			fa.setType(FansAttentionType.TYPE_ATTENTION.getCode());
			fansAttentionService.saveFansattention(fa);
		}
		//我的粉丝
		else if("myFans".equals(opterType)) {
			//关注后将变成单向粉丝变成互粉粉丝
			fansattention.setFollowing("true");
			fansAttentionService.updateFansattentionFollow(fansattention);
			//新增关注记录
			Fansattention fa = fansAttentionService.findByUsernameFansname(fansattention).get(0);
			fa.setFollowing("true");
			fa.setFollowme("true");
			fa.setType(FansAttentionType.TYPE_ATTENTION.getCode());
			fansAttentionService.saveFansattention(fa);
		}
		//添加指定用户为关注
		else if("addAttention".equals(opterType)) {
			//判断粉丝中是否有记录
			Fansattention fa = new Fansattention();
			fa.setUsername(fansattention.getUsername());
			fa.setFansattentionusername(fansattention.getFansattentionusername());

			//处理粉丝
			fa.setType(FansAttentionType.TYPE_FANS.getCode());
			Fansattention faFans = fansAttentionService.findByUsernameFansnameType(fa);
			//没有记录
			if(faFans != null) {
				//粉丝中有记录
				faFans.setFollowing("true");
				fansAttentionService.updateFansattentionFollow(faFans);
			}

			//处理关注
			fa.setType(FansAttentionType.TYPE_ATTENTION.getCode());
			Fansattention faAttention = fansAttentionService.findByUsernameFansnameType(fa);
			//没有记录
			if(faAttention == null) {
				//添加到我的关注
				fa = setFansattention(user, fansattention.getUsername(), FansAttentionType.TYPE_ATTENTION.getCode());
				fa.setFollowing("true");
				if(faFans != null) {
					fa.setFollowme(faFans.getFollowme());
				}
				fansAttentionService.saveFansattention(fa);
			} else {
				//关注中有记录
				faAttention.setFollowing("true");
				if(faFans != null) {
					fa.setFollowme(faFans.getFollowme());
				}
				fansAttentionService.updateFansattentionFollow(faAttention);
			}
		}
	}
}